//
//  UIScrollView+Extension.swift
//  SwiftBaseProject
//
//  Created by 苏州巨细 on 2018/5/18.
//  Copyright © 2018年 苏州巨细. All rights reserved.
//

import Foundation
import MJRefresh


extension UIScrollView {
    
    /// 自动结束刷新状态，配合MJRefresh使用
    ///
    /// - Parameters:
    ///   - currentPageIndex: 当前的页码
    ///   - resultListCount: 请求结果数据数量
    ///   - sizeCount: 默认结果数量
    ///   - isFailure: 是否是请求失败
    func autoEndRefreshAndHideTableFooterView(currentPageIndex: inout NSInteger, resultListCount :NSInteger, sizeCount: NSInteger = 10, isFailure: Bool = false) -> () {
        if !isFailure {
            //当页码为0的时候重新刷新没有数据
            if let footer = self.mj_footer {
                if currentPageIndex == 0 {
                    footer.endRefreshingWithNoMoreData()
                }
                
                if self.mj_footer.isHidden {
                    footer.isHidden = false
                }
                //当第一次请求为空数据的时候，隐藏footerView
                if resultListCount == 0 && currentPageIndex == 0 {
                    footer.isHidden = true
                }
            }
            
            if resultListCount == 0 && currentPageIndex > 0 {
                currentPageIndex = currentPageIndex-1
            }
        }
        
        if let footer = self.mj_footer {
            footer.endRefreshing()
        }
        
        if let header = self.mj_header {
            header.endRefreshing()
        }
        
        //没有更多数据要放到刷新之后
        if (self.mj_footer != nil) && resultListCount < sizeCount && !isFailure {
            self.mj_footer.endRefreshingWithNoMoreData()
        }
        
    }
}
